package com.huikeportal.service.impl;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.huikeportal.dao.SquareKequnMapper;
import com.huikeportal.model.KequnAnalysisModel;
import com.huikeportal.model.ReportGraphData;
import com.huikeportal.model.UserInfo;
import com.huikeportal.service.FootfallGlobalService;
import com.huikeportal.service.SquareKequnService;


@Service("SquareKequnService")
public class SquareKequnServiceImpl implements SquareKequnService {
	
	
	@Autowired
	SquareKequnMapper squareKequnMapper;
	
	@Autowired
	private FootfallGlobalService footfallGlobalService;
	

	public String getChinaWeek(int weekInt){
		String weekStr="星期一";
		switch (weekInt) {
		case 1:
			weekStr="星期日";
			break;
		case 2:
			weekStr="星期一";
			break;
		case 3:
			weekStr="星期二";
			break;
		case 4:
			weekStr="星期三";
			break;
		case 5:
			weekStr="星期四";
			break;
		case 6:
			weekStr="星期五";
			break;
		case 7:
			weekStr="星期六";
			break;
		default:
			break;
		}
		return weekStr;
	}
	
	/**
	 * 数字千分位
	 * @param text
	 * @return
	 */
	public  String fmtMicrometer(String text)  
    {  
        DecimalFormat df = null;  
        if(text.indexOf(".") > 0)
        {  
            if(text.length() - text.indexOf(".")-1 == 0)  
            {  
                df = new DecimalFormat("###,##0.");  
            }else if(text.length() - text.indexOf(".")-1 == 1)  
            {  
                df = new DecimalFormat("###,##0.0");  
            }else  
            {  
                df = new DecimalFormat("###,##0.00");  
            }  
        }else   
        {  
            df = new DecimalFormat("###,##0");  
        }  
        double number = 0.0;  
        try {  
             number = Double.parseDouble(text);  
        } catch (Exception e) {  
            number = 0.0;  
        }  
        return df.format(number);  
    }
	
	/**前台获取图表数据  */
	public StringBuffer getGlobalTable(List<ReportGraphData> list,String timeType_table,UserInfo userInfo,String siteId) throws Exception {
		
		//计算table列宽
		int rowNum = 5;
		float rowWidth = 0;
		
		SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd");
		StringBuffer stringTable=new StringBuffer();
		String thxingqi = "";
		if("day".equals(timeType_table)){
			rowWidth = (float) ((100-5.4)/(rowNum));
			thxingqi = "<th  style='width: "+rowWidth+"%;'>星期</th>";
		}else{
			rowWidth = (float) ((100-5.4)/(rowNum)-1);
			thxingqi = "";
		}
		stringTable.append("<table class='indextable xyliebiao widthall'>");
		stringTable.append("<tr><th class='xykongbai'></th>"
								+"<th class='xyxuhao'>编号</th>"
								+"<th  style='width: "+rowWidth+"%;'>日期</th>");
		stringTable.append(thxingqi);
        stringTable.append("<th style='width: " + rowWidth +
            "%;'>新顾客数（人）</th>");

        stringTable.append("<th style='width: " + rowWidth +
            "%;'>老顾客数（人）</th>");

		stringTable.append("<th class='xykongbai'></th></tr>");
		 for (int i = 0; i < list.size(); i++){
			String tdxingqi = "";
			String tdriqi = "";
			if("hour".equals(timeType_table)){
				tdxingqi = "";
				tdriqi = "<td>"+list.get(i).getDatatime()+"</td>";
			}else if("day".equals(timeType_table)){
				Calendar cl=Calendar.getInstance();
				cl.setTime(sf.parse(list.get(i).getDatatime()));
				int weekInt=cl.get(Calendar.DAY_OF_WEEK);
				tdxingqi = "<td>"+getChinaWeek(weekInt)+"</td>";
				tdriqi = "<td>"+list.get(i).getDatatime()+"</td>";
			}else if("week".equals(timeType_table)){
				tdxingqi = "";
				tdriqi = "<td>"+list.get(i).getYear()+"-"+list.get(i).getWeek()+"</td>";
			}else if("month".equals(timeType_table)){
				tdxingqi = "";
				tdriqi = "<td>"+list.get(i).getYear()+"-"+list.get(i).getMonth()+"</td>";
			}else{
				tdxingqi = "";
				tdriqi = "<td>"+list.get(i).getYear()+"</td>";
			}
			stringTable.append("<tr>");
			stringTable.append("<td class='xykongbai'></td>"
					+"<td class='xyxuhao'>"+(i + 1)+"</td>");
			stringTable.append(tdriqi);
			stringTable.append(tdxingqi);
            stringTable.append("<td>" +
                fmtMicrometer(list.get(i).getNewCustomerNum()) + "</td>");
            stringTable.append("<td>" +
                fmtMicrometer(list.get(i).getOldCustomer()) + "</td>");

			stringTable.append("<td></td>"); 
			stringTable.append("</tr>");
         }
		 stringTable.append("</table>");
		return stringTable;
	}
	
	public HashMap<String, Double> getPeiNweOld(List<ReportGraphData> list){
		double  newCustomerNum = 0;
		double  oldCustomer = 0;
		for (int i = 0; i < list.size(); i++){
			String newCustomerNumStr = list.get(i).getNewCustomerNum();
			if(newCustomerNumStr != null && !"".equals(newCustomerNumStr)){
				newCustomerNum = newCustomerNum + Double.parseDouble(newCustomerNumStr);
			}else{
				newCustomerNum = newCustomerNum + 0;
			}
			String oldCustomerStr = list.get(i).getOldCustomer();
			if(oldCustomerStr != null && !"".equals(oldCustomerStr)){
				oldCustomer = oldCustomer + Double.parseDouble(oldCustomerStr);
			}else{
				oldCustomer = oldCustomer + 0;
			}
		 }
		HashMap<String, Double> retMap = new HashMap<String, Double>();
		retMap.put("newCustomerNum", newCustomerNum);
		retMap.put("oldCustomer", oldCustomer);
		return retMap;
	}
	
	public List<KequnAnalysisModel> getStartEndCome(HashMap<String , Object> map){
		
		List<KequnAnalysisModel> resultList=new ArrayList<KequnAnalysisModel>();
		
		String timeType="";
		if(map.get("timeType")!=null && !map.get("timeType").toString().equals("")){
			timeType=map.get("timeType").toString();
		}
		String timeType_table="";
		if(map.get("timeType_table")!=null && !map.get("timeType_table").toString().equals("")){
			timeType_table=map.get("timeType_table").toString();
		}
		String from="";
		if(map.get("startDate")!=null && !map.get("startDate").toString().equals("")){
			from=map.get("startDate").toString();
		}
		String to="";
		if(map.get("endDate")!=null && !map.get("endDate").toString().equals("")){
			to=map.get("endDate").toString();
		}
		String siteId="";
		if(map.get("siteId")!=null && !map.get("siteId").toString().equals("")){
			siteId=map.get("siteId").toString();
		}
		UserInfo userInfo=null;
		if(map.get("userInfo")!=null){
			userInfo=(UserInfo) map.get("userInfo");
		}
		                
		
		
		//根据日周月年的不同需要的参数map
		HashMap<String, Object> pramMap1 = new HashMap<String, Object>();
		try {
			pramMap1 = footfallGlobalService.getparam(timeType_table,timeType,from,to);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		
		if(siteId.equals("")){
//			pramMap1.put("siteid",siteAllInfo.getSiteid());//放入场所id
		}else{
			pramMap1.put("siteid",siteId);//放入场所id
		}
		pramMap1.put("userId",userInfo.getUserId());
		
		resultList = squareKequnMapper.getStartEndCome(pramMap1);
		/**和应该有的日期对比，如果该日期没有数据设置为空，添加到list*/
//		List<String> listDate=(List<String>)pramMap1.get("Betweens");
		 List<String> lDate = new ArrayList<String>();  
        for(int i = 0;i < 24;i++){
        	String hh ="";
        	if(i<10){
        		hh= hh+"0"+i+":00";
        	}else{
        		hh= hh+i+":00";
        	}
        	lDate.add(hh);
        }
		if(resultList.size() != lDate.size()){
			for (int da=0;da<lDate.size();da++){
				Boolean flg=false;
				for(int rep=0;rep< resultList.size();rep++){
					if(lDate.get(da).equals(resultList.get(rep).getTime())){
						flg=true;
					}
				}
				if(flg){
					continue;
				}else{
					KequnAnalysisModel kequnAnalysisModel=new KequnAnalysisModel();
					kequnAnalysisModel.setTime(lDate.get(da));
					kequnAnalysisModel.setDate(pramMap1.get("startDate").toString());
					kequnAnalysisModel.init();
					resultList.add(da, kequnAnalysisModel);
				}
			}
		}
		return resultList;
		
	}

	public HashMap<String, Double> getPeiComeFreq(HashMap<String , Object> map) {
		List<KequnAnalysisModel> resultList = new ArrayList<KequnAnalysisModel>();
		String timeType = "";
		if(map.get("timeType")!=null && !map.get("timeType").toString().equals("")){
			timeType=map.get("timeType").toString();
		}
		String timeType_table="";
		if(map.get("timeType_table")!=null && !map.get("timeType_table").toString().equals("")){
			timeType_table=map.get("timeType_table").toString();
		}
		String from="";
		if(map.get("startDate")!=null && !map.get("startDate").toString().equals("")){
			from=map.get("startDate").toString();
		}
		String to="";
		if(map.get("endDate")!=null && !map.get("endDate").toString().equals("")){
			to=map.get("endDate").toString();
		}
		String siteId="";
		if(map.get("siteId")!=null && !map.get("siteId").toString().equals("")){
			siteId=map.get("siteId").toString();
		}
		UserInfo userInfo=null;
		if(map.get("userInfo")!=null){
			userInfo=(UserInfo) map.get("userInfo");
		}
		//根据日周月年的不同需要的参数map
		HashMap<String, Object> pramMapday = new HashMap<String, Object>();
		try {
			pramMapday = footfallGlobalService.getparam(timeType_table,timeType,from,to);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		
		
		//根据日周月年的不同需要的参数map
		HashMap<String, Object> pramMap1 = new HashMap<String, Object>();
		try {
			SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd");
			Calendar clFrom = Calendar.getInstance(); 
			clFrom.setTime(sf.parse(pramMapday.get("startDate").toString()));
			Calendar clTo = Calendar.getInstance(); 
			clTo.setTime(sf.parse(pramMapday.get("endDate").toString()));
			
			pramMap1.put("startYear", clFrom.get(Calendar.YEAR));
			pramMap1.put("endYear", clTo.get(Calendar.YEAR));
			pramMap1.put("startMonth", clFrom.get(Calendar.MONTH)+1);
			pramMap1.put("endMonth", clTo.get(Calendar.MONTH)+1);
			if(pramMap1.get("startMonth").toString().length()==1){
				pramMap1.put("startMonth", "0"+pramMap1.get("startMonth").toString());
			}
			if(pramMap1.get("endMonth").toString().length()==1){
				pramMap1.put("endMonth", "0"+pramMap1.get("endMonth").toString());
			}
			//根据开始时间结束时间算出时间段
			List<String> listMonth = footfallGlobalService.getMonthsBetweenTwoMonth(pramMap1.get("startYear").toString(),pramMap1.get("startMonth").toString(),
					pramMap1.get("endYear").toString(),pramMap1.get("endMonth").toString());
			pramMap1.put("Betweens", listMonth);
			
		} catch (ParseException e) {
			e.printStackTrace();
		}
		if(siteId.equals("")){
//			pramMap1.put("siteid",siteAllInfo.getSiteid());//放入场所id
		}else{
			pramMap1.put("siteid",siteId);//放入场所id
		}
		pramMap1.put("userId",userInfo.getUserId());
		resultList = squareKequnMapper.getPeiComeFreq(pramMap1);
		
		KequnAnalysisModel kequnAnalysisModel;
		if(resultList == null || resultList.size() == 0){
			kequnAnalysisModel = new KequnAnalysisModel();
		}else{
			kequnAnalysisModel = resultList.get(0);
		}
		HashMap<String, Double> retMap = new HashMap<String, Double>();
		String one = kequnAnalysisModel.getOne();
		retMap.put("one",(one == null ||"".equals(one))?0:Double.parseDouble(one));
		String twoToFive = kequnAnalysisModel.getTwoToFive();
		retMap.put("twoToFive",(twoToFive == null ||"".equals(twoToFive))?0:Double.parseDouble(twoToFive));
		String fiveToTen = kequnAnalysisModel.getFiveToTen();
		retMap.put("fiveToTen",(fiveToTen == null ||"".equals(fiveToTen))?0:Double.parseDouble(fiveToTen));
		String tenToFifteen = kequnAnalysisModel.getTenToFifteen();
		retMap.put("tenToFifteen",(tenToFifteen == null ||"".equals(tenToFifteen))?0:Double.parseDouble(tenToFifteen));
		String FifteenToTwentyone = kequnAnalysisModel.getFifteenToTwentyone();
		retMap.put("FifteenToTwentyone",(FifteenToTwentyone == null ||"".equals(FifteenToTwentyone))?0:Double.parseDouble(FifteenToTwentyone));
		String twentyoneTotwentyEight = kequnAnalysisModel.getTwentyoneTotwentyEight();
		retMap.put("twentyoneTotwentyEight",(twentyoneTotwentyEight == null ||"".equals(twentyoneTotwentyEight))?0:Double.parseDouble(twentyoneTotwentyEight));
		String twentyEightTothirtyone = kequnAnalysisModel.getTwentyEightTothirtyone();
		retMap.put("twentyEightTothirtyone",(twentyEightTothirtyone == null ||"".equals(twentyEightTothirtyone))?0:Double.parseDouble(twentyEightTothirtyone));
		return retMap;
		
	}

	public HashMap<String, Double> getPeiPhoneTerminal(HashMap<String , Object> map) {
		List<KequnAnalysisModel> resultList=new ArrayList<KequnAnalysisModel>();
		String timeType="";
		if(map.get("timeType")!=null && !map.get("timeType").toString().equals("")){
			timeType=map.get("timeType").toString();
		}
		String timeType_table="";
		if(map.get("timeType_table")!=null && !map.get("timeType_table").toString().equals("")){
			timeType_table=map.get("timeType_table").toString();
		}
		String from="";
		if(map.get("startDate")!=null && !map.get("startDate").toString().equals("")){
			from=map.get("startDate").toString();
		}
		String to="";
		if(map.get("endDate")!=null && !map.get("endDate").toString().equals("")){
			to=map.get("endDate").toString();
		}
		String siteId="";
		if(map.get("siteId")!=null && !map.get("siteId").toString().equals("")){
			siteId=map.get("siteId").toString();
		}
		UserInfo userInfo=null;
		if(map.get("userInfo")!=null){
			userInfo=(UserInfo) map.get("userInfo");
		}
		//根据日周月年的不同需要的参数map
		HashMap<String, Object> pramMap1 = new HashMap<String, Object>();
		try {
			pramMap1 = footfallGlobalService.getparam(timeType_table,timeType,from,to);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		if(siteId.equals("")){
//			pramMap1.put("siteid",siteAllInfo.getSiteid());//放入场所id
		}else{
			pramMap1.put("siteid",siteId);//放入场所id
		}
		pramMap1.put("userId",userInfo.getUserId());
		resultList = squareKequnMapper.getPeiPhoneTerminal(pramMap1);
		
		KequnAnalysisModel kequnAnalysisModel;
		if(resultList == null || resultList.size() == 0){
			kequnAnalysisModel = new KequnAnalysisModel();
		}else{
			kequnAnalysisModel = resultList.get(0);
		}
		HashMap<String, Double> retMap = new HashMap<String, Double>();
		String iphone = kequnAnalysisModel.getIphone();
		retMap.put("iphone",(iphone == null ||"".equals(iphone))?0:Double.parseDouble(iphone));
		String samsung = kequnAnalysisModel.getSamsung();
		retMap.put("samsung",(samsung == null ||"".equals(samsung))?0:Double.parseDouble(samsung));
		String huawei = kequnAnalysisModel.getHuawei();
		retMap.put("huawei",(huawei == null ||"".equals(huawei))?0:Double.parseDouble(huawei));
		String xiaomi = kequnAnalysisModel.getXiaomi();
		retMap.put("xiaomi",(xiaomi == null ||"".equals(xiaomi))?0:Double.parseDouble(xiaomi));
		String others = kequnAnalysisModel.getOthers();
		retMap.put("others",(others == null ||"".equals(others))?0:Double.parseDouble(others));
		String unknown = kequnAnalysisModel.getUnknown();
		retMap.put("unknown",(unknown == null ||"".equals(unknown))?0:Double.parseDouble(unknown));
		return retMap;
	}

	public HashMap<String, Double> getPeiRetentionavg(HashMap<String , Object> map) {
		List<KequnAnalysisModel> resultList=new ArrayList<KequnAnalysisModel>();
		String timeType="";
		if(map.get("timeType")!=null && !map.get("timeType").toString().equals("")){
			timeType=map.get("timeType").toString();
		}
		String timeType_table="";
		if(map.get("timeType_table")!=null && !map.get("timeType_table").toString().equals("")){
			timeType_table=map.get("timeType_table").toString();
		}
		String from="";
		if(map.get("startDate")!=null && !map.get("startDate").toString().equals("")){
			from=map.get("startDate").toString();
		}
		String to="";
		if(map.get("endDate")!=null && !map.get("endDate").toString().equals("")){
			to=map.get("endDate").toString();
		}
		String siteId="";
		if(map.get("siteId")!=null && !map.get("siteId").toString().equals("")){
			siteId=map.get("siteId").toString();
		}
		UserInfo userInfo=null;
		if(map.get("userInfo")!=null){
			userInfo=(UserInfo) map.get("userInfo");
		}
		
		List<String> types = footfallGlobalService.getSiteTypes(siteId);
		String siteyype;
		if(types != null && types.size()>0){
			siteyype = types.get(0);
		}else{
			return null;
		}
		//根据日周月年的不同需要的参数map
		HashMap<String, Object> pramMap1 = new HashMap<String, Object>();
		try {
			pramMap1 = footfallGlobalService.getparam(timeType_table,timeType,from,to);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		if(siteId.equals("")){
//			pramMap1.put("siteid",siteAllInfo.getSiteid());//放入场所id
		}else{
			pramMap1.put("siteid",siteId);//放入场所id
		}
		pramMap1.put("userId",userInfo.getUserId());
		
		if(siteyype.equals("600")){
			resultList = squareKequnMapper.getPeiRetentionavg(pramMap1);
		}else if(siteyype.equals("300")){
			resultList = squareKequnMapper.getPeiRetentionavg1(pramMap1);
		}else{
			return null;
		}
		KequnAnalysisModel kequnAnalysisModel;
		if(resultList == null || resultList.size() == 0){
			kequnAnalysisModel = new KequnAnalysisModel();
		}else{
			kequnAnalysisModel = resultList.get(0);
		}
		HashMap<String, Double> retMap = new HashMap<String, Double>();
		if(siteyype.equals("600")){
			String storeZoreTwo = kequnAnalysisModel.getStoreZoreTwo();
			retMap.put("storeZoreTwo",(storeZoreTwo == null ||"".equals(storeZoreTwo))?0:Double.parseDouble(storeZoreTwo));
			String storeTwoFive = kequnAnalysisModel.getStoreTwoFive();
			retMap.put("storeTwoFive",(storeTwoFive == null ||"".equals(storeTwoFive))?0:Double.parseDouble(storeTwoFive));
			String storeFiveTen = kequnAnalysisModel.getStoreFiveTen();
			retMap.put("storeFiveTen",(storeFiveTen == null ||"".equals(storeFiveTen))?0:Double.parseDouble(storeFiveTen));
			String storeTenThirty = kequnAnalysisModel.getStoreTenThirty();
			retMap.put("storeTenThirty",(storeTenThirty == null ||"".equals(storeTenThirty))?0:Double.parseDouble(storeTenThirty));
			String storeThirtySixty = kequnAnalysisModel.getStoreThirtySixty();
			retMap.put("storeThirtySixty",(storeThirtySixty == null ||"".equals(storeThirtySixty))?0:Double.parseDouble(storeThirtySixty));
			String storeSixtyOneHtwenty = kequnAnalysisModel.getStoreSixtyOneHtwenty();
			retMap.put("storeSixtyOneHtwenty",(storeSixtyOneHtwenty == null ||"".equals(storeSixtyOneHtwenty))?0:Double.parseDouble(storeSixtyOneHtwenty));
			String OnehundredtwentyUp = kequnAnalysisModel.getOnehundredtwentyUp();
			retMap.put("OnehundredtwentyUp",(OnehundredtwentyUp == null ||"".equals(OnehundredtwentyUp))?0:Double.parseDouble(OnehundredtwentyUp));
		}else if(siteyype.equals("300")){
			String squareZoreTen = kequnAnalysisModel.getSquareZoreTen();
			retMap.put("squareZoreTen",(squareZoreTen == null ||"".equals(squareZoreTen))?0:Double.parseDouble(squareZoreTen));
			String squareTenThirty = kequnAnalysisModel.getSquareTenThirty();
			retMap.put("squareTenThirty",(squareTenThirty == null ||"".equals(squareTenThirty))?0:Double.parseDouble(squareTenThirty));
			String squareThirtySixty = kequnAnalysisModel.getSquareThirtySixty();
			retMap.put("squareThirtySixty",(squareThirtySixty == null ||"".equals(squareThirtySixty))?0:Double.parseDouble(squareThirtySixty));
			String squareSixtyOneHtwenty = kequnAnalysisModel.getSquareSixtyOneHtwenty();
			retMap.put("squareSixtyOneHtwenty",(squareSixtyOneHtwenty == null ||"".equals(squareSixtyOneHtwenty))?0:Double.parseDouble(squareSixtyOneHtwenty));
			String squareOneHtwentyToOneHEight = kequnAnalysisModel.getSquareOneHtwentyToOneHEight();
			retMap.put("squareOneHtwentyToOneHEight",(squareOneHtwentyToOneHEight == null ||"".equals(squareOneHtwentyToOneHEight))?0:Double.parseDouble(squareOneHtwentyToOneHEight));
			String squareOneHeightToTwoHfourty = kequnAnalysisModel.getSquareOneHeightToTwoHfourty();
			retMap.put("squareOneHeightToTwoHfourty",(squareOneHeightToTwoHfourty == null ||"".equals(squareOneHeightToTwoHfourty))?0:Double.parseDouble(squareOneHeightToTwoHfourty));
			String squareTwoHfourtyUp = kequnAnalysisModel.getSquareTwoHfourtyUp();
			retMap.put("squareTwoHfourtyUp",(squareTwoHfourtyUp == null ||"".equals(squareTwoHfourtyUp))?0:Double.parseDouble(squareTwoHfourtyUp));
		}
		retMap.put("siteyype", Double.parseDouble(siteyype));
		
		return retMap;
	}
}
